<?php
error_reporting(E_ALL & ~E_NOTICE);
@ob_start();
@session_start();

	if(!isset($_SESSION['firstname']) || !isset($_SESSION['lastname']) || !isset($_SESSION['username']) || !isset($_SESSION['user_group_id'])){
    echo "<script>window.location = '../index.php';</script>";
    exit();
	}
	
	if(isset($_SESSION['user_group_id'])){
	if($_SESSION['user_group_id']!=0) {
	echo "<script>window.location = '../index.php';</script>";
   	exit();
	}
	}
	
include("../connect/connect.php");
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Shop Management System</title>
<link rel=StyleSheet HREF="style.css" TYPE="text/css" MEDIA=screen>
<script language="javascript">

function check_number(ch) {
	var len, digit;
		if(ch == " "){ 
		return false;
		len=0;
		}else{
		len = ch.length;
		}
	for(var i=0 ; i<len ; i++)
		{
		digit = ch.charAt(i)
		if(digit >="0" && digit <="9"){
		;
		}else{
		return false; 
		} 
		} 
	return true;
}


function fncAdd()
{
	if(!check_number(document.frm.quantity.value) || document.frm.quantity.value == "" )
	{
	alert('กรุณากรอกจำนวนเป็นตัวเลข');
	document.frm.quantity.focus();
	return false;
	} else {
	return true;
	}
}

function fncSubmit()
{

	if(document.formsumall.sum.value == "0.00")
	{
		alert('กรุณาทำรายการก่อน');
		document.frm.input.focus();
		return false;
	}
	
	if(document.frmsum.show.value == "0.00")
	{
		alert('กรุณาระบุจำนวนเงินที่ได้รับ');
		document.frmsum.show.focus();
		return false;
	}
	
	if(document.frmchange.show2.value <= "0")
	{
		alert('กรุณาคิดเงินใหม่');
		document.frmsum.show.focus();
		return false;
	}
	
	if(confirm('ยืนยันการสั่งซื้อ')==true)
	{
		document.form1.submit();
	}
}

function fncSubmit2()
{

	if(document.formsumall.sum.value == "0.00")
	{
		alert('กรุณาทำรายการก่อน');
		document.frm.input.focus();
		return false;
	}
	
	if(confirm('ยืนยันการบันทึกรายการลูกหนี้')==true)
	{
		window.location='<?php echo $_SERVER['PHP_SELF'];?>?action=stock2';
	}
}

function open_popup(){
	

	if(document.formsumall.sum.value == "0.00")
	{
		alert('กรุณาทำรายการก่อน');
		document.frm.input.focus();
		return false;
	}
	
	if(document.frmsum.show.value == "0.00")
	{
		alert('กรุณาระบุจำนวนเงินที่ได้รับ');
		document.frmsum.show.focus();
		return false;
	}
	
	if(document.frmchange.show2.value <= "0")
	{
		alert('กรุณาคิดเงินใหม่');
		document.frmsum.show.focus();
		return false;
	}

	if(confirm('ยืนยันการพิมพ์ใบเสร็จ')==true)
	{
	window.open('bill.php',null,"height=550,width=430,status=no,toolbar=no,menubar=no,location=no,scrollbars=1");

	setTimeout("location.href = 'index.php';",1000);
	}
}

function open_popup2(){

	if(document.formsumall.sum.value == "0.00")
	{
		alert('กรุณาทำรายการก่อน');
		document.frm.input.focus();
		return false;
	}

	if(confirm('ยืนยันการพิมพ์ใบแจ้งหนี้')==true)
	{
	window.open('billname2.php',null,"height=550,width=430,status=no,toolbar=no,menubar=no,location=no,scrollbars=1");

	setTimeout("location.href = 'index.php';",1000);
	}
}
</script>
<style type="text/css">
<!--
body,td,th {
	font-family: Tahoma;
	font-size: 14px;
}
.style1 {font-size: 13px}
a:link {
	text-decoration: none;
	color: #0000FF;
}
a:visited {
	text-decoration: none;
	color: #0000FF;
}
a:hover {
	text-decoration: none;
	color: #0000FF;
}
a:active {
	text-decoration: none;
	color: #0000FF;
}
-->

</style>
<?php

//============ Check ว่ามีซ้ำแล้วหรือยังถ้ามีแล้วให้ + เพิ่มไป
if($_POST["input"] != "")
{
	for($i=0;$i<=count($_SESSION["strProductID"]);$i++)
	{
			if($_SESSION["strProductID"][$i] == $_POST["input"])
			{
			
			$qtyold = $_SESSION["strQuanlity"][$i];
			$qtysum = $_POST["quantity"];
			$qtynew = $qtyold+$qtysum;

			$_SESSION["strQuanlity"][$i] = $qtynew;
			session_write_close();
			
			header("location:$_SERVER[PHP_SELF]");
			exit();
			}
	}
}

//============ ถ้ามีการเลือกรายการสินค้าให้เก็บลง Session
if(trim($_POST["input"]) != "")
{
	$Querycode = "SELECT code FROM product WHERE code = '".$_POST["input"]."'";
	$dbquerycode = mysql_query($Querycode);
	$resultcode = mysql_fetch_array($dbquerycode);
	
	if($resultcode["code"]==$_POST["input"]){
	$_SESSION["strP"]=$_SESSION["strP"]+1;
	$_SESSION["strProductID"][$_SESSION[strP]]=$_POST["input"];
	$_SESSION["strQuanlity"][$_SESSION[strP]]=$_POST["quantity"];
	session_write_close();
	
	header("location:$_SERVER[PHP_SELF]");
	} else {
	$nocode = "<center><strong><font color=red>กรุณากรอกรหัสสินค้าให้ถูกต้อง</font></strong></center>";	
	}
}

//============ กรณีลบรายการสั่งซื้อ
if(trim($_GET["action"]) == "Del")
{
	$_SESSION["strProductID"][$_GET[P]]="";
	$_SESSION["strQuanlity"][$_GET[P]]="";
	session_write_close();
	header("location:$_SERVER[PHP_SELF]");
}	

//============ กรณีลบยกเลิกรายการ
if(trim($_GET["action"]) == "listcancel")
{
	$_SESSION["strP"]="";
	$_SESSION["strProductID"]="";
	$_SESSION["strQuanlity"]="";
	$_SESSION["strshow"]="";
	$_SESSION["name_bill"] = "";
	$_SESSION["address_bill"] = "";
	$_SESSION["name_bill2"] = "";
	$_SESSION["address_bill2"] = "";
	$_SESSION["billno"] = "";
	$_SESSION['billstatus'] = "";
		
	session_write_close();
	header("location:$_SERVER[PHP_SELF]");
}	

//=========แสดงจำนวนในช่องรับเงิน
if(trim($_POST["show"]) != "" )
{
		
	$show2 = $_POST['show'];
	$arrshow2 = explode(',', $show2);
	foreach ($arrshow2 as $v) {
		$newshow2 .=  $v;
	}
		$_SESSION["strshow"]= $newshow2;
		session_write_close();
}


//=======คิดเงิน
if(isset($_REQUEST["oneooo"])) {

	$strold = $_SESSION["strshow"];
	$strnew = $_REQUEST["oneooo"];

	$_SESSION["strshow"] = $strold+$strnew;
	session_write_close();
	
	header("location:$_SERVER[PHP_SELF]");
}

if(isset($_REQUEST["fivehundred"])) {

	$strold = $_SESSION["strshow"];
	$strnew = $_REQUEST["fivehundred"];

	$_SESSION["strshow"] = $strold+$strnew;
	session_write_close();
	
	header("location:$_SERVER[PHP_SELF]");
}

if(isset($_REQUEST["onehundred"])) {

	$strold = $_SESSION["strshow"];
	$strnew = $_REQUEST["onehundred"];

	$_SESSION["strshow"] = $strold+$strnew;
	session_write_close();
	
	header("location:$_SERVER[PHP_SELF]");
}

if(isset($_REQUEST["fifty"])) {

	$strold = $_SESSION["strshow"];
	$strnew = $_REQUEST["fifty"];

	$_SESSION["strshow"] = $strold+$strnew;
	session_write_close();
	
	header("location:$_SERVER[PHP_SELF]");
}

if(isset($_REQUEST["twenty"])) {

	$strold = $_SESSION["strshow"];
	$strnew = $_REQUEST["twenty"];

	$_SESSION["strshow"] = $strold+$strnew;
	session_write_close();
	
	header("location:$_SERVER[PHP_SELF]");
}

if(isset($_REQUEST["ten"])) {

	$strold = $_SESSION["strshow"];
	$strnew = $_REQUEST["ten"];

	$_SESSION["strshow"] = $strold+$strnew;
	session_write_close();
	
	header("location:$_SERVER[PHP_SELF]");
}

if(isset($_REQUEST["five"])) {

	$strold = $_SESSION["strshow"];
	$strnew = $_REQUEST["five"];

	$_SESSION["strshow"] = $strold+$strnew;
	session_write_close();
	
	header("location:$_SERVER[PHP_SELF]");
}

if(isset($_REQUEST["two"])) {

	$strold = $_SESSION["strshow"];
	$strnew = $_REQUEST["two"];

	$_SESSION["strshow"] = $strold+$strnew;
	session_write_close();
	
	header("location:$_SERVER[PHP_SELF]");
}

if(isset($_REQUEST["one"])) {

	$strold = $_SESSION["strshow"];
	$strnew = $_REQUEST["one"];

	$_SESSION["strshow"] = $strold+$strnew;
	session_write_close();
	
	header("location:$_SERVER[PHP_SELF]");
}

if(isset($_REQUEST["dotfifty"])) {

	$strold = $_SESSION["strshow"];
	$strnew = $_REQUEST["dotfifty"];

	$_SESSION["strshow"] = $strold+$strnew;
	session_write_close();
	
	header("location:$_SERVER[PHP_SELF]");
}

if(isset($_REQUEST["dottwentyfive"])) {

	$strold = $_SESSION["strshow"];
	$strnew = $_REQUEST["dottwentyfive"];

	$_SESSION["strshow"] = $strold+$strnew;
	session_write_close();
	
	header("location:$_SERVER[PHP_SELF]");
}

if(isset($_REQUEST["clear"])) {

	$_SESSION["strshow"]='0';
	session_write_close();
	
	header("location:$_SERVER[PHP_SELF]");
}

?>

</head>

<script>
function setFocus(){
	document.frm.input.focus();
}

</script>
<body onload="setFocus()">
<table align="center" class="all">
  <tr>
    <td bgcolor="#333333"><table width="100%" height="570" border="0" cellspacing="0" cellpadding="0">
      <tr>
        <td valign="top" bgcolor="#ABC8E2">
          <table border="0" cellpadding="0" cellspacing="0" class="list">
            <tr>
              <td align="right" valign="top" bgcolor="#f5f5f5"><div id="scroll_product"><table width="100%" border="0" cellspacing="1" cellpadding="2">
                <tr class="blue">
                  <td width="7%">ลำดับ</td>
                  <td width="19%">รหัสสินค้า</td>
                  <td width="35%">รายการสินค้า</td>
                  <td width="10%">ราคา</td>
                  <td width="8%">จำนวน</td>
                  <td width="12%">รวม</td>
                  <td width="9%">ลบ</td>
                </tr>
<?php

//============ ทำการแสงรายการที่ได้เลือกว่ามีกี่รายการ

$strNum=0;
$strTotal=0;
$cost=0;
for($i=0;$i<=count($_SESSION["strProductID"]);$i++)
{
//============ แสดงจำนวนรายการสินค้า
	$Query = "SELECT code,name,cost,price FROM product WHERE 1=1 AND code = '".$_SESSION["strProductID"]["$i"]."'";
	$dbquery = mysql_query($Query);
	$result= mysql_fetch_array($dbquery);
	
	if($result)
		{
		$strNum++;
?>
                <tr class="white">
                  <td align="center"><?php echo $strNum;?></td>
                  <td align="left" style="padding-left:10px"><?php echo $result['code'];?></td>
                  <td align="left" style="padding-left:20px"><?php echo $result['name'];?></td>
                  <td align="right" style="padding-right:15px"><?php echo $result['price'];?></td>
                  <td align="right" style="padding-right:20px"><?php echo $_SESSION["strQuanlity"]["$i"];?></td>
                  <td align="right" style="padding-right:15px"><?php echo "".number_format(($result["price"])*$_SESSION["strQuanlity"]["$i"], 2,'.',',');?></td>
                  <td align="center"><a href="javascript:if(confirm('ลบรายการสินค้า')==true){window.location='<?php echo $_SERVER['PHP_SELF'];?>?action=Del&amp;P=<?php echo $i;?>';}"><img src="../image/delete.png" width="15" height="15" border="0" /></a></td>
                </tr>
<?php 
		$strTotal=$strTotal+(($result["price"])*$_SESSION["strQuanlity"]["$i"]);
		$cost=$cost+(($result["cost"])*$_SESSION["strQuanlity"]["$i"]);
		}
} 

?>
              </table>
<?php
	echo $nocode;
			if($strNum==0)
				{
				echo "<br><center><strong><font color=red>ไม่มีรายการสินค้า</font></strong></center>";
				}


//=============ตัดสต็อก
if($_POST["action"]=="stock")
{

	for($i=0;$i<=count($_SESSION["strProductID"]);$i++)
		{	
		$Query1 = "SELECT * FROM product WHERE 1=1 AND code = '".$_SESSION["strProductID"]["$i"]."'";
		$dbquery1 = mysql_query($Query1);
		$result1 = mysql_fetch_array($dbquery1);
		//$cost = $result
			if($result1)
				{
				$Proid=$_SESSION["strProductID"]["$i"];
				$Quanlity=$_SESSION["strQuanlity"]["$i"];
				$sql = "update product set quantity=quantity-$Quanlity where code='$Proid'";
				$dbquery = mysql_query($sql);
				
				//เพิ่มสินค้าขายดี
				$sql2 = "update product set selling=selling+$Quanlity where code='$Proid'";
				$dbquery2 = mysql_query($sql2);
				}
		}

// Insert Order

		$strSQL = "INSERT INTO sale (date,amount,cost) VALUES ('".date("Y-m-d")."','".$strTotal."','".$cost."') ON DUPLICATE KEY UPDATE amount=amount+'".$strTotal."' , cost=cost+'".$cost."'";
		$dbquery = mysql_query($strSQL);

		$_SESSION["strP"]="";
		$_SESSION["strProductID"]="";
		$_SESSION["strQuanlity"]="";
		$_SESSION["strshow"]="";
		$_SESSION["name_bill"] = "";
		$_SESSION["address_bill"] = "";
		$_SESSION["name_bill2"] = "";
		$_SESSION["address_bill2"] = "";
		$_SESSION["billno"] = "";
		$_SESSION['billstatus'] = "";

		session_write_close();
		header("location:index.php");
}

//=============ตัดสต็อก2 บันทึกรายการลูกหนี้
if($_GET["action"]=="stock2")
{
// Insert ตารางลูกหนี้

		$strSQL = "INSERT INTO debtor (deb_date,deb_name,deb_address,deb_amount,deb_cost,deb_no) VALUES ('".date("Y-m-d")."','".$_SESSION["name_bill2"]."','".$_SESSION["address_bill2"]."','".$strTotal."','".$cost."','".$_SESSION["billno"]."')";
		$dbquery = mysql_query($strSQL);
		
		$sDebtor = mysql_query("SELECT max(deb_id) as deb_id FROM debtor");
		$sRow = mysql_fetch_array($sDebtor);

	for($i=0;$i<=count($_SESSION["strProductID"]);$i++)
		{
		$Query1 = "SELECT * FROM product WHERE 1=1 AND code = '".$_SESSION["strProductID"]["$i"]."'";
		$dbquery1 = mysql_query($Query1);
		$result1 = mysql_fetch_array($dbquery1);
		//$cost = $result
			if($result1)
				{
				//ตัดสต็อก
				$Proid=$_SESSION["strProductID"]["$i"];
				$Quanlity=$_SESSION["strQuanlity"]["$i"];
				$sql = "update product set quantity=quantity-$Quanlity where code='$Proid'";
				$dbquery = mysql_query($sql);
				
				//เพิ่มสินค้าขายดี
				$sql2 = "update product set selling=selling+$Quanlity where code='$Proid'";
				$dbquery2 = mysql_query($sql2);
				
				//เพิ่มรายการเข้าข้อมูลลูกหนี้
				$dQuery = mysql_query("INSERT INTO debtor_bill (debtor_id,product_id,quantity,cost,price) VALUE ('".$sRow['deb_id']."','".$result1['product_id']."','".$Quanlity."','".$result1['cost']."','".$result1['price']."')");
					
				}
		}
		
		
		$_SESSION["strP"]="";
		$_SESSION["strProductID"]="";
		$_SESSION["strQuanlity"]="";
		$_SESSION["strshow"]="";
		$_SESSION["name_bill"] = "";
		$_SESSION["address_bill"] = "";
		$_SESSION["name_bill2"] = "";
		$_SESSION["address_bill2"] = "";
		$_SESSION["billno"] = "";
		$_SESSION['billstatus'] = "";
		
		session_write_close();
		header("location:index.php");
}
?>
              </div></td>
            </tr>
          </table>
          <table width="100%" border="0" cellspacing="0" cellpadding="0">
            <tr>
              <td width="30%" valign="top"><form name="frm" method="post" onsubmit="return fncAdd();" action="<?php $_SERVER['PHP_SELF']; ?>">
                <table class="input" width="240" border="0" align="left" cellpadding="0" cellspacing="0">
                  <tr>
                  <td class="coloradd">รหัสสินค้า</td>
                </tr>
                <tr>
                  <td width="240"><div align="left">
                    <input name="input" id="input" type="text" autocomplete="off" style="width:200px; text-align:center; height:30px; font-size:25px"/>
                  </div></td>
                </tr>
                <tr>
                  <td class="input">จำนวน</td>
                </tr>
                <tr>
                  <td><div align="left">
                    <input name="quantity" type="text" id="quantity" autocomplete="off" style="width:100px; text-align:center; height:30px; font-size:25px" value="1"/>
                    <input type="submit" name="Submit" value="เพิ่ม" style="width:90px; height:37px; text-align:center; font-size:18px" />
                  </div>
                    <span class="style1"><br />ชื่อพนักงาน : <?php echo $_SESSION["firstname"]." ".$_SESSION["lastname"]; ?><br />
                    ตำแหน่ง : พนักงาน   
                    <a href="../logout.php">&nbsp; ออกจากระบบ</a><br />
                    </span></td>
                </tr>
              </table></form></td>
              <td width="70%" valign="top">

              <table width="100%" height="150" border="0" cellspacing="0" cellpadding="0">
                <tr>
                  <td width="309" align="center"><form name="frmsum1" id="frmsum1" method="post" action="">
                    <input type="submit" name="oneooo" id="oneooo" value="1000" style="height:30px; width:48px" />
                    <input type="submit" name="fivehundred" id="fiveooo" value="500" style="height:30px; width:48px"  />
                    <input type="submit" name="onehundred" id="oneoo" value="100" style="height:30px; width:48px"  />
                    <input type="submit" name="fifty" id="fiveo" value="50" style="height:30px; width:48px"  />
                    <input type="submit" name="twenty" id="twoo" value="20" style="height:30px; width:48px" />
      <input type="submit" name="ten" id="ten" value="10" style="height:30px; width:48px"  />
                                        <br />
                    <input type="submit" name="five" id="five" value="5" style="height:30px; width:48px"  />
                    <input type="submit" name="two" id="two" value="2" style="height:30px; width:48px"  />
                    <input type="submit" name="one" id="one" value="1" style="height:30px; width:48px"  />
                    <input type="submit" name="dotfifty" id="0.50" value="0.50" style="height:30px; width:48px"  />
                    <input type="submit" name="dottwentyfive" id="0.25" value="0.25" style="height:30px; width:48px"  />
                    <input type="submit" name="clear" id="clear" value="c" style="height:30px; width:48px"  />
               </form>   </td>
                  <td align="right"><form id="formsumall" name="formsumall" method="post" action=""><font color="#FF0000">
                    <input name="sum" type="text" id="sum" style="width:200px; text-align:right; height:50px; font-size:50px; background-color:#FFF; color: red" value="<?php echo "".number_format($strTotal, 2,'.',',');?>" readonly="readonly"/>
                  </font></form></td>
                  <td width="30">&nbsp;</td>
                </tr>
                <tr>
                  <td height="29" rowspan="2" align="center" valign="bottom">
                    <form id="form1" name="form1" method="post" action="">
                      <input name="BtnCalu4" type="button" id="BtnCalu4" value="บันทึกรายการ" style="width:140px; height:37px; font-size:18px" <?php if($_SESSION['billstatus']=="1"){ echo " "; } else { echo "disabled=\"disabled\""; } ?> onclick="JavaScript:return fncSubmit();" />
                      <input name="BtnCalu3" type="button" id="BtnCalu3" value="พิมพ์ใบเสร็จ" style="width:140px; height:37px; font-size:18px" onclick="open_popup()" />
                      <input name="action" type="hidden" id="action" value="stock" />
                      <input name="BtnCalu42" type="button" id="BtnCalu42" value="บันทึกลูกหนี้" style="width:140px; height:37px; font-size:18px" <?php if($_SESSION['billstatus']=="2"){ echo " "; } else { echo "disabled=\"disabled\""; } ?> onclick="JavaScript:return fncSubmit2();" />
                      <input name="BtnCalu32" type="button" id="BtnCalu32" value="พิมพ์ใบแจ้งหนี้" style="width:140px; height:37px; font-size:18px" onclick="open_popup2()" />
                      <input name="BtnCalu" type="button" id="BtnCalu" value="ยกเลิกรายการ" style="width:140px; height:37px; font-size:18px" <?php if($_SESSION['strProductID']!=""){ echo " "; } else { echo "disabled=\"disabled\""; } ?>  onclick="javascript:if(confirm('ยืนยันการยกเลิกรายการ')==true){window.location='<?php echo $_SERVER['PHP_SELF'];?>?action=listcancel';}" />
                    <input name="BtnCalu5" type="button" id="BtnCalu5" value="จัดการสินค้า" style="width:140px; height:37px; font-size:18px" onclick="window.location='../manager/product_manage.php'" />
                    </form></td>
                  <td width="200" align="right" valign="bottom"><form name="frmsum" id="frmsum" method="post" action=""><font color="#FF0000">&nbsp;
                    </font><font color="#000">รับเงิน :</font><font color="#FF0000">
                      <input name="show" type="text" id="show" autocomplete="off" style="width:120px; text-align:right; height:25px; font-size:25px; color:#1859cd"  value="<?php 
if($_SESSION["strshow"]!=""){
 echo number_format($_SESSION["strshow"], 2,'.',','); 
} else {
echo "0.00";
}
 ?>" maxlength="10"/>
                    </font></form></td>
                  <td>&nbsp;</td>
                </tr>
                <tr>
                  <?php 
 if(!$_SESSION["strshow"]=="")
 {
 $aa= $_SESSION["strshow"]-$strTotal ; 
 }
 ?>
                  <td height="29" align="right" valign="top"><form name="frmchange" id="frmchange" method="post" action=""><font color="#FF0000">&nbsp;
                    </font><font color="#000">ทอนเงิน : </font><font color="#FF0000">
                      <input name="show2" type="text" id="show2" style="width:120px; text-align:right; height:25px; font-size:25px; color: #1859cd" value="<?php echo "".number_format($aa, 2,'.',',');?>" readonly="readonly"/>
                    </font></form></td>
                  <td>&nbsp;</td>
                </tr>
              </table></td>
            </tr>
          </table></td>
      </tr>
    </table></td>
  </tr>
</table>
</body>
</html>